package com.wsd.bookkeeping.controller;

import com.wsd.bookkeeping.entity.Account;
import com.wsd.bookkeeping.entity.AccountUser;
import com.wsd.bookkeeping.form.InviteForm;
import com.wsd.bookkeeping.form.PermissionForm;
import com.wsd.bookkeeping.service.AccountService;
import com.wsd.bookkeeping.service.AccountUserService;
import com.wsd.bookkeeping.service.RightService;
import com.wsd.common.entity.ResponseEntity;
import com.wsd.common.utils.DateUtils;
import com.wsd.common.utils.ResponseUtils;
import com.wsd.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/account")
@Slf4j
public class AccountController {


    @Resource
    private AccountService accountService;

    @Resource
    private AccountUserService accountUserService;

    @Resource
    private RightService rightService;

    /**
     * 获取邀请二维码
     * @param response 响应
     */
    @GetMapping("/{bookId}/invite/image/of/{userId}/to/{scene}")
    public void getInviteImage(InviteForm inviteForm, HttpServletResponse response) throws Exception {
        // 将二维码写入到输出流
        ServletOutputStream outputStream = response.getOutputStream();
        accountService.writeInviteImageToOutputStream(inviteForm, outputStream);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 邀请用户加入当前账本
     */
    @PostMapping("/{bookId}/{userId}/invite/{inviteUserId}")
    public ResponseEntity inviteUser(AccountUser accountUser) {
        if (!accountService.isEfficientBook(accountUser.getBookId())) {
            throw new RRException("账本已被删除");
        }

        accountUser.setParticipantDate(DateUtils.currentDateTimeNString());

        // 设置用户基本权限信息
        PermissionForm userPermission = new PermissionForm();
        userPermission.setUserId(accountUser.getUserId());
        userPermission.setBookId(accountUser.getBookId());
        List<Integer> permissionList = new ArrayList<>();
//        permissionList.add(1);
//        permissionList.add(2);
//        permissionList.add(3);
        userPermission.setPermissions(permissionList);

        System.err.println(userPermission);
        Boolean saveStatus = rightService.saveOrUpdateUserPermission(userPermission);
        System.err.println("初始化用户权限" + (saveStatus ? "成功" : "失败"));


        return ResponseUtils.ret(accountUserService.save(accountUser));
    }

    /**
     * 修改预算
     * @param account
     */
    @PutMapping("/budget")
    public ResponseEntity updateBudget(@RequestBody Account account) {
        return ResponseUtils.ret(accountService.updateById(account));
    }

    /**
     * 根据账本ID修改账本信息
     * @param account
     */
    @PutMapping("/")
    public ResponseEntity updateAccountById(@RequestBody Account account) {
        return ResponseUtils.ret(accountService.updateById(account));
    }

    /**
     * 新增账本
     * @param account
     * @param request
     */
    @PostMapping("/")
    public ResponseEntity create(@RequestBody Account account, HttpServletRequest request) {
        account.setCreateIp(request.getRemoteAddr());
        account.setCreateDate(DateUtils.currentDateNString());
        return accountService.save(account) ? ResponseEntity.success() : ResponseEntity.error();
    }

    /**
     * 根据账本ID删除账本
     * @param id
     */
    @DeleteMapping("/{id}")
    public ResponseEntity remove(@PathVariable("id") Integer id) throws Exception {
        return accountService.removeAccountById(id) ? ResponseEntity.success() : ResponseEntity.error();
    }

    /**
     * 根据账本ID查询账本信息
     * @param id
     */
    @GetMapping("/{id}")
    public ResponseEntity queryByAccountId(@PathVariable("id") Integer id) {
        return ResponseEntity.success().put("account", accountService.getById(id));
    }

    /**
     * 查询用户账单列表
     * 查询用户个人账本和加入的账本
     */
    @GetMapping("/list/{userId}")
    public ResponseEntity queryPage(@PathVariable Integer userId) throws InterruptedException {
        // todo bug
        return ResponseEntity.success().put("list", accountService.queryUserAccountList(userId));
    }

    /**
     * 查询当前账本用户的消费信息
     * @param bookId 账本ID
     */
    @GetMapping("/{bookId}/info/{userId}")
    public ResponseEntity queryUserInfoListByBookId(@PathVariable("bookId") Integer bookId) {
        // todo
        return ResponseEntity.success().put("info", accountService.queryUserInfoListByBookId(bookId));
    }

    /**
     * 查询账本的预算金额
     * @param bookId 账本Id
     */
    @GetMapping("/budget/{bookId}")
    public ResponseEntity queryBudget(@PathVariable Integer bookId) {
        BigDecimal budget = accountService.getById(bookId).getBudget();
        return ResponseEntity.success().put("budget", budget);
    }

    /**
     * 账本人员信息
     * @param bookId 账本id
     */
    @GetMapping("/users/list/{bookId}")
    public ResponseEntity queryBookUsersByBookId(@PathVariable Integer bookId) {
        return ResponseEntity.success()
                .put("list", accountService.queryAccountUsersByBookId(bookId))
                .put("admin", accountService.queryAccountAdminByBookId(bookId));
    }



}



